package com.carrental.vehicle.service.impl;

import com.carrental.common.api.PageResult;
import com.carrental.vehicle.service.VehicleUsageService;
import com.carrental.vehicle.vo.VehicleUsageStatVO;
import com.carrental.vehicle.vo.VehicleUsageDetailVO;
import com.carrental.vehicle.vo.VehicleWearVO;
import com.carrental.vehicle.mapper.VehicleUsageMapper;
import com.carrental.vehicle.mapper.VehicleMapper;
import com.carrental.vehicle.entity.Vehicle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 车辆使用统计服务实现类
 */
@Service
public class VehicleUsageServiceImpl implements VehicleUsageService {

    @Autowired
    private VehicleUsageMapper vehicleUsageMapper;
    
    @Autowired
    private VehicleMapper vehicleMapper;

    @Override
    public PageResult<VehicleUsageStatVO> getVehicleUsageStatistics(Integer current, Integer size, 
            String licensePlate, Long brandId, Integer type, String startDate, String endDate) {
        
        // 这里实现分页查询车辆使用统计数据的逻辑
        // 实际项目中应该从数据库查询数据
        
        // 为了演示，这里返回模拟数据
        List<VehicleUsageStatVO> records = generateMockVehicleUsageStats();
        
        // 根据查询条件过滤
        if (licensePlate != null && !licensePlate.isEmpty()) {
            records = records.stream()
                    .filter(item -> item.getLicensePlate().contains(licensePlate))
                    .collect(Collectors.toList());
        }
        
        if (brandId != null) {
            records = records.stream()
                    .filter(item -> item.getBrandName().equals(getBrandNameById(brandId)))
                    .collect(Collectors.toList());
        }
        
        if (type != null) {
            records = records.stream()
                    .filter(item -> item.getTypeName().equals(getVehicleTypeName(type)))
                    .collect(Collectors.toList());
        }
        
        // 计算总记录数
        int total = records.size();
        
        // 分页处理
        int startIndex = (current - 1) * size;
        int endIndex = Math.min(startIndex + size, total);
        
        if (startIndex < total) {
            records = records.subList(startIndex, endIndex);
        } else {
            records = new ArrayList<>();
        }
        
        // 创建图表数据
        Map<String, Object> chartData = generateMockChartData();
        
        // 创建返回结果
        PageResult<VehicleUsageStatVO> result = new PageResult<>();
        result.setRecords(records);
        result.setTotal(total);
        result.setCurrent(current);
        result.setSize(size);
        result.setPages((total + size - 1) / size);
        result.setExtra("stats", generateMockStats());
        result.setExtra("chartData", chartData);
        
        return result;
    }

    @Override
    public VehicleUsageDetailVO getVehicleUsageDetail(Long vehicleId) {
        // 这里实现获取车辆使用详情的逻辑
        // 实际项目中应该从数据库查询数据
        
        // 为了演示，这里返回模拟数据
        VehicleUsageDetailVO detail = new VehicleUsageDetailVO();
        detail.setVehicleId(vehicleId);
        
        // 模拟查询车辆基本信息
        Vehicle vehicle = vehicleMapper.selectById(vehicleId);
        if (vehicle != null) {
            detail.setLicensePlate(vehicle.getLicensePlate());
            detail.setVehicleName(vehicle.getName());
            detail.setBrandName(getBrandNameById(vehicle.getBrandId()));
        } else {
            // 模拟数据
            detail.setLicensePlate("京A12345");
            detail.setVehicleName("奥迪A6L");
            detail.setBrandName("奥迪");
        }
        
        detail.setRentalCount(12);
        detail.setTotalDuration(120);
        detail.setTotalMileage(8500.0);
        
        // 模拟租赁记录
        List<VehicleUsageDetailVO.RentalRecordVO> records = new ArrayList<>();
        LocalDate endDate = LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        
        for (int i = 0; i < 10; i++) {
            VehicleUsageDetailVO.RentalRecordVO record = new VehicleUsageDetailVO.RentalRecordVO();
            record.setOrderId("ORD" + (20250001 + i));
            record.setCustomerName("客户" + (i + 1));
            
            LocalDate startDate = endDate.minusDays(10);
            record.setStartTime(startDate.format(formatter));
            record.setEndTime(endDate.format(formatter));
            
            int duration = (int) ChronoUnit.DAYS.between(startDate, endDate);
            record.setDuration(duration);
            
            double mileage = 500 + Math.random() * 500;
            record.setMileage(Math.round(mileage * 10) / 10.0);
            
            double dailyMileage = mileage / duration;
            record.setDailyMileage(Math.round(dailyMileage * 10) / 10.0);
            
            // 判断里程是否异常
            record.setIsAbnormal(dailyMileage > 80);
            
            records.add(record);
            endDate = startDate.minusDays(1);
        }
        
        detail.setRentalRecords(records);
        
        // 模拟趋势数据
        List<Map<String, Object>> trendData = new ArrayList<>();
        LocalDate now = LocalDate.now();
        
        for (int i = 0; i < 12; i++) {
            Map<String, Object> data = new HashMap<>();
            LocalDate month = now.minusMonths(i);
            data.put("date", month.format(DateTimeFormatter.ofPattern("yyyy-MM")));
            data.put("mileage", 500 + Math.random() * 300);
            data.put("duration", 8 + Math.random() * 5);
            trendData.add(data);
        }
        
        detail.setTrendData(trendData);
        
        return detail;
    }

    @Override
    public VehicleWearVO getVehicleWearAnalysis(Long vehicleId) {
        // 这里实现获取车辆损耗评估的逻辑
        // 实际项目中应该从数据库查询数据
        
        // 为了演示，这里返回模拟数据
        VehicleWearVO wear = new VehicleWearVO();
        wear.setVehicleId(vehicleId);
        
        // 模拟查询车辆基本信息
        Vehicle vehicle = vehicleMapper.selectById(vehicleId);
        if (vehicle != null) {
            wear.setLicensePlate(vehicle.getLicensePlate());
            wear.setVehicleName(vehicle.getName());
            wear.setProductionYear(vehicle.getProductionYear());
        } else {
            // 模拟数据
            wear.setLicensePlate("京A12345");
            wear.setVehicleName("奥迪A6L");
            wear.setProductionYear(2022);
        }
        
        // 计算车辆年龄
        int currentYear = LocalDate.now().getYear();
        int age = currentYear - wear.getProductionYear();
        wear.setAge(age);
        
        // 模拟总里程和使用时长
        wear.setTotalMileage(36500.0);
        wear.setTotalDuration(365);
        
        // 计算损耗等级
        int wearLevel = calculateWearLevel(age, wear.getTotalMileage());
        wear.setWearLevel(wearLevel);
        
        // 计算剩余使用寿命
        double remainingLife = calculateRemainingLife(age, wear.getTotalMileage());
        wear.setRemainingLife(remainingLife);
        
        // 计算损耗百分比
        double wearPercentage = calculateWearPercentage(age, wear.getTotalMileage());
        wear.setWearPercentage(wearPercentage);
        
        // 计算里程损耗百分比
        double mileageWearPercentage = calculateMileageWearPercentage(wear.getTotalMileage());
        wear.setMileageWearPercentage(mileageWearPercentage);
        
        // 计算时间损耗百分比
        double timeWearPercentage = calculateTimeWearPercentage(age);
        wear.setTimeWearPercentage(timeWearPercentage);
        
        // 生成评估建议
        String suggestion = generateWearSuggestion(wearLevel, mileageWearPercentage, timeWearPercentage);
        wear.setSuggestion(suggestion);
        
        return wear;
    }

    @Override
    public void exportVehicleUsageStatistics(HttpServletResponse response, String licensePlate, 
            Long brandId, Integer type, String startDate, String endDate) {
        
        try {
            // 设置响应头
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("车辆使用统计数据", "UTF-8") + ".xlsx";
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            
            // 这里实现导出Excel的逻辑
            // 实际项目中应该从数据库查询数据并写入Excel
            
            // 为了演示，这里只是设置响应，不实际生成Excel文件
            response.getWriter().write("车辆使用统计数据导出成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void generateVehicleWearReport(HttpServletResponse response, Long vehicleId) {
        try {
            // 设置响应头
            response.setContentType("application/pdf");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("车辆损耗评估报告", "UTF-8") + ".pdf";
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
            
            // 这里实现生成PDF报告的逻辑
            // 实际项目中应该从数据库查询数据并生成PDF
            
            // 为了演示，这里只是设置响应，不实际生成PDF文件
            response.getWriter().write("车辆损耗评估报告生成成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    // 模拟方法：生成车辆使用统计数据
    private List<VehicleUsageStatVO> generateMockVehicleUsageStats() {
        List<VehicleUsageStatVO> list = new ArrayList<>();
        
        for (int i = 1; i <= 20; i++) {
            VehicleUsageStatVO vo = new VehicleUsageStatVO();
            vo.setVehicleId((long) i);
            vo.setLicensePlate("京A" + (10000 + i));
            
            int type = (i % 5) + 1;
            String brandName = getBrandByIndex(i % 10);
            
            vo.setVehicleName(getVehicleNameByBrand(brandName, i % 3));
            vo.setBrandName(brandName);
            vo.setTypeName(getVehicleTypeName(type));
            
            vo.setRentalCount(10 + (i % 10));
            vo.setTotalDuration(100 + (i * 5));
            vo.setAvgDuration((double) vo.getTotalDuration() / vo.getRentalCount());
            
            vo.setTotalMileage(3000.0 + (i * 500.0));
            vo.setAvgMileage(vo.getTotalMileage() / vo.getTotalDuration());
            
            vo.setWearLevel((i % 5) + 1);
            vo.setHasAbnormalMileage(i % 7 == 0);
            
            list.add(vo);
        }
        
        return list;
    }
    
    // 模拟方法：获取车辆品牌
    private String getBrandByIndex(int index) {
        String[] brands = {"奥迪", "宝马", "奔驰", "丰田", "本田", "大众", "福特", "现代", "日产", "别克"};
        return brands[index];
    }
    
    // 模拟方法：根据品牌ID获取品牌名称
    private String getBrandNameById(Long brandId) {
        if (brandId == null) return "未知";
        
        // 这里应该从数据库查询，这里简化处理
        String[] brands = {"奥迪", "宝马", "奔驰", "丰田", "本田", "大众", "福特", "现代", "日产", "别克"};
        int index = (int) (brandId % 10);
        return brands[index];
    }
    
    // 模拟方法：根据品牌获取车辆名称
    private String getVehicleNameByBrand(String brand, int modelIndex) {
        Map<String, String[]> modelMap = new HashMap<>();
        modelMap.put("奥迪", new String[]{"A4L", "A6L", "Q5L"});
        modelMap.put("宝马", new String[]{"3系", "5系", "X5"});
        modelMap.put("奔驰", new String[]{"C级", "E级", "GLC"});
        modelMap.put("丰田", new String[]{"卡罗拉", "凯美瑞", "汉兰达"});
        modelMap.put("本田", new String[]{"思域", "雅阁", "CR-V"});
        modelMap.put("大众", new String[]{"朗逸", "帕萨特", "途观"});
        modelMap.put("福特", new String[]{"福克斯", "蒙迪欧", "锐界"});
        modelMap.put("现代", new String[]{"朗动", "索纳塔", "途胜"});
        modelMap.put("日产", new String[]{"轩逸", "天籁", "奇骏"});
        modelMap.put("别克", new String[]{"英朗", "君威", "昂科威"});
        
        String[] models = modelMap.getOrDefault(brand, new String[]{"未知型号"});
        return brand + " " + models[modelIndex % models.length];
    }
    
    // 模拟方法：获取车辆类型名称
    private String getVehicleTypeName(int type) {
        String[] types = {"未知", "经济型", "舒适型", "豪华型", "SUV", "MPV"};
        return types[type % types.length];
    }
    
    // 模拟方法：生成统计数据
    private Map<String, Object> generateMockStats() {
        Map<String, Object> stats = new HashMap<>();
        stats.put("avgRentalCount", 15.5);
        stats.put("avgRentalDuration", 12.8);
        stats.put("avgMileage", 65.3);
        return stats;
    }
    
    // 模拟方法：生成图表数据
    private Map<String, Object> generateMockChartData() {
        Map<String, Object> chartData = new HashMap<>();
        
        // 使用频率TOP10
        List<Map<String, Object>> frequencyData = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Map<String, Object> data = new HashMap<>();
            data.put("licensePlate", "京A" + (10000 + i));
            data.put("count", 20 - i);
            frequencyData.add(data);
        }
        chartData.put("frequencyData", frequencyData);
        
        // 里程TOP10
        List<Map<String, Object>> mileageData = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Map<String, Object> data = new HashMap<>();
            data.put("licensePlate", "京B" + (10000 + i));
            data.put("mileage", 10000 - (i * 500));
            mileageData.add(data);
        }
        chartData.put("mileageData", mileageData);
        
        // 散点图数据
        List<Map<String, Object>> scatterData = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            Map<String, Object> data = new HashMap<>();
            data.put("licensePlate", "京" + (char)('A' + (i % 5)) + (10000 + i));
            data.put("duration", 100 + (i * 10));
            data.put("mileage", 3000 + (i * 300) + (Math.random() * 1000));
            data.put("abnormal", i % 10 == 0);
            scatterData.add(data);
        }
        chartData.put("scatterData", scatterData);
        
        return chartData;
    }
    
    // 计算损耗等级 (1-5)
    private int calculateWearLevel(int age, double totalMileage) {
        // 假设正常使用5年，10万公里为中度损耗
        double ageFactor = age / 5.0;
        double mileageFactor = totalMileage / 100000.0;
        
        double factor = (ageFactor + mileageFactor) / 2.0;
        
        if (factor < 0.4) return 1; // 轻微
        if (factor < 0.8) return 2; // 正常
        if (factor < 1.2) return 3; // 中度
        if (factor < 1.6) return 4; // 严重
        return 5; // 极重
    }
    
    // 计算剩余使用寿命 (年)
    private double calculateRemainingLife(int age, double totalMileage) {
        // 假设正常使用寿命为10年，20万公里
        double ageRemaining = Math.max(0, 10 - age);
        double mileageRemaining = Math.max(0, 200000 - totalMileage) / 20000; // 每年2万公里
        
        return Math.min(ageRemaining, mileageRemaining);
    }
    
    // 计算损耗百分比
    private double calculateWearPercentage(int age, double totalMileage) {
        // 假设正常使用寿命为10年，20万公里
        double agePercentage = Math.min(1.0, age / 10.0) * 100;
        double mileagePercentage = Math.min(1.0, totalMileage / 200000.0) * 100;
        
        return (agePercentage + mileagePercentage) / 2.0;
    }
    
    // 计算里程损耗百分比
    private double calculateMileageWearPercentage(double totalMileage) {
        // 假设正常使用寿命为20万公里
        return Math.min(1.0, totalMileage / 200000.0) * 100;
    }
    
    // 计算时间损耗百分比
    private double calculateTimeWearPercentage(int age) {
        // 假设正常使用寿命为10年
        return Math.min(1.0, age / 10.0) * 100;
    }
    
    // 生成损耗评估建议
    private String generateWearSuggestion(int wearLevel, double mileageWearPercentage, double timeWearPercentage) {
        switch (wearLevel) {
            case 1:
                return "车辆状况良好，建议正常保养维护，定期检查油液，保持良好驾驶习惯。";
            case 2:
                return "车辆正常磨损，建议按时进行常规保养，检查制动系统和轮胎磨损情况。";
            case 3:
                return "车辆中度磨损，建议增加保养频次，重点检查发动机、变速箱和悬挂系统，考虑更换关键易损部件。";
            case 4:
                return "车辆损耗严重，建议全面检修，更换主要磨损部件，评估是否需要降低租赁频次或调整租赁价格。";
            case 5:
                return "车辆极度磨损，建议停止租赁服务，进行彻底大修或考虑报废处理，更新车队。";
            default:
                return "未能评估车辆状况，请联系专业技术人员进行检查。";
        }
    }
} 